from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import SQLAlchemyError
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime

from app import db


class Users(db.Model):

	__talbename__ = 'pyjwt_user'
	id = db.Column(db.Integer, primary_key=True)
	email = db.Column(db.String(250),  unique=True, nullable=False)
	username = db.Column(db.String(250),  unique=True, nullable=False)
	password = db.Column(db.String(250))
	login_time = db.Column(db.Integer)
	# login_time = db.Column(db.TIMESTAMP(True), nullable=False)

	def __init__(self, username, password, email):
		self.username = username
		self.password = self.set_password(password)		# modify
		self.email = email

	def __str__(self):
		return "Users(id {})".format(self.id)

	def set_password(self, password):
		return generate_password_hash(password)

	def check_password(self, hash, password):
		return check_password_hash(hash, password)

	@classmethod
	def get_by_id(cls, id):
		return cls.query.filter_by(id=id).first()

	def add(self):		# modify
		db.session.add(self)
		return session_commit()

	def update(self):
		return session_commit()

	def delete_by_id(self, id):
		self.query.filter_by(id=id).delete()


#: Common method for db
def session_commit():
	try:
		db.session.commit()
	except SQLAlchemyError as e:
		db.session.rollback()
		e_reason = str(e)
		return e_reason